<template>
  <div style="background: #f5f7fa; min-height: 100vh; padding: 40px 0;">
    <div style="background: #fff; padding: 24px 24px 12px 24px; margin: 0 40px; border-radius: 6px;">
      <!-- 查询条件 -->
      <el-form :inline="true" size="small" style="margin-bottom: 16px;">
        <el-form-item label="名称">
          <el-input v-model="searchForm.title" placeholder="请输入" style="width: 160px;" @input="onFormChange" clearable/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" style="width: 160px;" @change="onFormChange" clearable>
            <el-option label="上线" :value="1" />
            <el-option label="下线" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="searchForm.date" type="daterange" range-separator="—" start-placeholder="开始日期"
                          end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 260px;" @change="onFormChange" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="primary" @click="showAddDialog" style="margin-left: 8px;">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%;">
        <el-table-column prop="noticeId" label="公告ID" width="80" align="center" />
        <el-table-column prop="title" label="公告标题" width="120" align="center" />
        <el-table-column prop="content" label="公告内容" />
        <el-table-column prop="noticeType" label="公告类型" width="100" align="center" />
        <el-table-column prop="username" label="发布人ID" width="100" align="center" />
        <el-table-column prop="startTime" label="生效时间" width="160" align="center" />
        <el-table-column prop="endTime" label="失效时间" width="160" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.status === 1 ? '上线' : '下线' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" align="center" />
        <el-table-column prop="updatedAt" label="更新时间" width="160" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-link type="primary" @click="showEditDialog(scope.row)">编辑</el-link>
            <el-popconfirm
                title="确定要删除这条公告吗？"
                @confirm="handleDelete(scope.row.noticeId)"
                confirm-button-text="确定"
                cancel-button-text="取消"
            >
              <el-button slot="reference" type="text" style="margin-left: 8px; color: #F56C6C;">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin: 24px 0 0 0; display: flex; justify-content: flex-end;">
        <el-pagination background layout="prev, pager, next, sizes, jumper" :total="total" :page-size="pageSize"
                       :current-page="currentPage" :page-sizes="[10, 20, 50]" @size-change="handleSizeChange"
                       @current-change="handlePageChange" />
      </div>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog title="新增公告" :visible.sync="addDialogVisible" width="600px">
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="addForm.title" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="addForm.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="公告类型" prop="noticeType">
          <el-input v-model="addForm.noticeType" />
        </el-form-item>
        <el-form-item label="发布人" prop="publisherId">
          <el-select v-model="addForm.publisherId" placeholder="请选择发布人">
            <el-option v-for="item in publisherList" :key="item.publisherId" :label="item.username"
                       :value="item.publisherId" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" prop="startTime">
          <el-date-picker v-model="addForm.startTime" type="datetime" placeholder="选择生效时间"
                          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="失效时间" prop="endTime">
          <el-date-picker v-model="addForm.endTime" type="datetime" placeholder="选择失效时间"
                          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择">
            <el-option label="上线" :value="1" />
            <el-option label="下线" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSave">保存</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑公告" :visible.sync="editDialogVisible" width="600px">
      <el-form :model="editForm" :rules="addFormRules" ref="editForm" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="editForm.title" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="editForm.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="公告类型" prop="noticeType">
          <el-input v-model="editForm.noticeType" />
        </el-form-item>
        <el-form-item label="发布人" prop="publisherId">
          <el-select v-model="editForm.publisherId" placeholder="请选择发布人">
            <el-option v-for="item in publisherList" :key="item.publisherId" :label="item.username"
                       :value="item.publisherId" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" prop="startTime">
          <el-date-picker v-model="editForm.startTime" type="datetime" placeholder="选择生效时间"
                          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="失效时间" prop="endTime">
          <el-date-picker v-model="editForm.endTime" type="datetime" placeholder="选择失效时间"
                          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择">
            <el-option label="上线" :value="1" />
            <el-option label="下线" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { Message } from 'element-ui'
import { debounce } from 'lodash'

export default {
  name: 'ContentNotice',
  data() {
    return {
      searchForm: {
        title: '',
        status: '',
        date: []
      },
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '新增公告',
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        title: '',
        content: '',
        noticeType: '',
        publisherId: '',
        startTime: '',
        endTime: '',
        status: 1
      },
      editForm: {
        noticeId: null,
        title: '',
        content: '',
        noticeType: '',
        publisherId: '',
        startTime: '',
        endTime: '',
        status: 1
      },
      addFormRules: {
        title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
        noticeType: [{ required: true, message: '请输入公告类型', trigger: 'blur' }],
        publisherId: [{ required: true, message: '请输入发布人ID', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择生效时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择失效时间', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      publisherList: []
    }
  },
  methods: {
    fetchData() {
      let params = {
        title: this.searchForm.title,
        status: this.searchForm.status,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      if (this.searchForm.date && this.searchForm.date.length === 2) {
        params.startTime = this.searchForm.date[0]
        params.endTime = this.searchForm.date[1]
      }
      axios.get('/notices/list', { params }).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
        // 整理发布人列表
        const publisherMap = {}
        this.tableData.forEach(item => {
          if (item.publisherId && item.username && !publisherMap[item.publisherId]) {
            publisherMap[item.publisherId] = item.username
          }
        })
        this.publisherList = Object.keys(publisherMap).map(id => ({
          publisherId: Number(id),
          username: publisherMap[id]
        }))
      })
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handlePageChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    showAddDialog() {
      this.addForm = {
        title: '',
        content: '',
        noticeType: '',
        publisherId: '',
        startTime: '',
        endTime: '',
        status: 1
      }
      this.addDialogVisible = true
    },
    showEditDialog(row) {
      this.editForm = {
        noticeId: row.noticeId,
        title: row.title || '',
        content: row.content || '',
        noticeType: row.noticeType || '',
        publisherId: row.publisherId || '',
        startTime: row.startTime || '',
        endTime: row.endTime || '',
        status: row.status
      }
      this.editDialogVisible = true
    },
    handleAddSave() {
      this.$refs.addForm.validate(valid => {
        if (!valid) return
        axios.post('/notices/add', this.addForm).then(() => {
          this.$message.success('新增成功')
          this.addDialogVisible = false
          this.fetchData()
        })
      })
    },
    handleEditSave() {
      this.$refs.editForm.validate(valid => {
        if (!valid) return
        axios.post('/notices/edit', this.editForm).then(() => {
          this.$message.success('编辑成功')
          this.editDialogVisible = false
          this.fetchData()
        })
      })
    },
    handleDelete(id) {
      axios.delete(`/notices/delete/${id}`).then(() => {
        Message.success('删除成功')
        this.fetchData()
      })
    },
    onFormChange: debounce(function () {
      this.currentPage = 1
      this.fetchData()
    }, 400)
  },
  mounted() {
    this.fetchData()
  }
}
</script>